package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.enums.StatusRecordEnum;
import com.xmy.cultivate.feign.erp_admin.IAdminFeignClient;
import com.xmy.cultivate.respons.LeaveApply;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 老师端-学生请假申请表-审批 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2024-11-10
 */
@RestController
@RequestMapping("/api/teacherMessage")
@Scope("prototype")
public class StudentLeaveApplyController extends BaseController {

    @Autowired
    IStudentLeaveApplyService studentLeaveApplyService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    IRecordCourseService iRecordCourseService;

    @Autowired
    IAdminFeignClient iAdminFeignClient;

    @Autowired
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    IRepairCourseService iRepairCourseService;





    /**
     * 老师端请假申请待处理
     */
//    @GetMapping("/getNotHandleLeaveApply")
//    public Result getNotHandleLeave(){
//        Long adminId = this.adminId;
//
////        Long adminId = 1600483308095930368L;
//
//
//        System.err.println("登录id="+adminId);
//
//        System.err.println("============老师端请假申请待处理=============");
//
//        if (adminId == null) {
//            return new Result(Code.GET_OK,"","获取不到adminId");
//        }
//        List<StudentLeaveApply> notHandleLeaveList = studentLeaveApplyService.getNotHandleLeaveList(adminId);
//
//        return new Result(Code.GET_OK, notHandleLeaveList, Code.GET_OK_MSG);
//
//    }

    /**
     * 查询请假申请列表
     * type 0待处理，1已处理
     */
    @GetMapping("/getLeaveApplyList")
    public Result getLeaveApplyList(@RequestParam(value = "type", required = true) Integer type) {
        Long adminId = this.adminId;

        //未处理
        if (type == 0) {
            List<LeaveApply> notHandleLeaveList = studentLeaveApplyService.getNotHandleLeaveList(adminId);
            return new Result(Code.GET_OK, notHandleLeaveList, Code.GET_OK_MSG);
        }
        //已处理
        if (type == 1) {
            List<LeaveApply> handleLeaveList = studentLeaveApplyService.getHandleLeaveList(adminId);
            return new Result(Code.GET_OK, handleLeaveList, Code.GET_OK_MSG);
        }

        return new Result(Code.ERROR, "", "请传type参数 0未处理 1已处理");

    }


    /**
     * 老师端请假申请已处理
     */
//    @GetMapping("/getHandleLeaveApply")
//    public Result getHandleLeave(){
//        Long adminId = this.adminId;
////        Long adminId = 1600483308095930368L;
//
//        System.err.println("=========老师端请假申请已处理adminId========="+adminId);
//
//        if (adminId == null) {
//            return new Result(Code.GET_OK,"","获取不到adminId");
//        }
//
//        List<StudentLeaveApply> notHandleLeaveList = studentLeaveApplyService.getHandleLeaveList(adminId);
//
//        return new Result(Code.GET_OK, notHandleLeaveList, Code.GET_OK_MSG);
//
//    }

    /**
     * 老师审核
     */
    @PutMapping("/updateStatus")
    public Result update(@RequestBody StudentLeaveApply studentLeaveApplyParam) {

        Long adminId = this.adminId;
        StudentLeaveApply studentLeaveApply = studentLeaveApplyService.getById(studentLeaveApplyParam.getId());
        if (adminId == null) {
            return new Result(Code.GET_OK, "", "数据不存在");
        }
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String dateTime = now.format(formatter);

        Integer status = studentLeaveApplyParam.getStatus();
        studentLeaveApply.setAuditTeacherId(adminId);
        studentLeaveApply.setStatus(status);
        studentLeaveApply.setRefuseReason(studentLeaveApplyParam.getRefuseReason());
        studentLeaveApply.setAuditDateTime(LocalDateTime.parse(dateTime, formatter));

        boolean rs;
        if (status == 1) {
            LocalDate schoolDate = studentLeaveApply.getSchoolDate();
            LocalDate nowLocalDate = LocalDate.now();
            if (schoolDate.isEqual(nowLocalDate)) {
                QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
                recordCourseQueryWrapper.eq("scheduling_detail_id", studentLeaveApply.getSchedulingDetailId());
                recordCourseQueryWrapper.eq("student_id", studentLeaveApply.getStudentId());
                recordCourseQueryWrapper.eq("status", 3);
                recordCourseQueryWrapper.last("limit 1");
                RecordCourse recordCourse = iRecordCourseService.getOne(recordCourseQueryWrapper);
                if (recordCourse != null) {
                    //旷课记录由旷课调整为请假
                    recordCourse.setStatus(StatusRecordEnum.LEAVE);
                    iAdminFeignClient.checkRecordStatus(recordCourse);
                }
            }


            QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
            repairCourseQueryWrapper.eq("out_scheduling_detail_id", studentLeaveApply.getSchedulingDetailId());
            repairCourseQueryWrapper.eq("student_id", studentLeaveApply.getStudentId());
            repairCourseQueryWrapper.and(i->i.eq("is_sign_in",1).or().eq("status",1).or().gt("end_date_time", LocalDateTime.now().withNano(0)));
            //repairCourseQueryWrapper.gt("end_date_time", LocalDateTime.now().withNano(0));
            repairCourseQueryWrapper.last("limit 1");
            RepairCourse repairCourse = iRepairCourseService.getOne(repairCourseQueryWrapper);
            if (repairCourse != null){
                return new Result(Code.ERROR, "", "该时间排课已经调出到："+repairCourse.getStartDateTime().toString().replace("T"," ")+"上课，不能再同意申请");
            }


            rs = studentLeaveApplyService.updateById(studentLeaveApply);

            Integer stuDeductHour = 3;
            StatusRecordEnum statusRecordEnum = StatusRecordEnum.LEAVE;
            Integer courseType = 1;
            Quarter quarter = iQuarterService.getOneForYearAndNum(studentLeaveApply.getYearPart(), studentLeaveApply.getQuarterNum());
            QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
            courseSchedulingDetailQueryWrapper.eq("id",studentLeaveApply.getSchedulingDetailId());

            /*courseSchedulingDetailQueryWrapper.eq("school_date", studentLeaveApply.getSchoolDate());
            courseSchedulingDetailQueryWrapper.le("end_date_time", studentLeaveApply.getEndDateTime());
            courseSchedulingDetailQueryWrapper.eq("deleted", 0);
            courseSchedulingDetailQueryWrapper.eq("status", 0);
            courseSchedulingDetailQueryWrapper.eq("is_lock", 0);
            courseSchedulingDetailQueryWrapper.eq("grade_id", studentLeaveApply.getGradeId());
            courseSchedulingDetailQueryWrapper.eq("year_part", quarter.getYearPart());
            courseSchedulingDetailQueryWrapper.eq("quarter", quarter.getNum());
            courseSchedulingDetailQueryWrapper.eq("grade_status", 1);//班级状态为正常的*/

            //获取排课信息
            List<CourseSchedulingDetail> courseSchedulingDetailList = iCourseSchedulingDetailService.getCourseSchedulingDetailList(courseSchedulingDetailQueryWrapper);
            for (CourseSchedulingDetail courseSchedulingDetail : courseSchedulingDetailList) {
                RecordCourse recordCourse = studentLeaveApplyService.addLeaveData(courseSchedulingDetail.getId(), studentLeaveApply.getStudentId(), stuDeductHour, statusRecordEnum, 1, courseType, quarter);
                if (recordCourse != null) {
                    //扣课时
                    iMqPushService.buckleHouse(recordCourse);
                }
            }
            return new Result(Code.UPDATE_OK, "", "已同意请假申请");
        } else if (status == 2) {
            try {
                Long schedulingDetailId = studentLeaveApply.getSchedulingDetailId();
                Long studentId = studentLeaveApply.getStudentId();
                QueryWrapper<RecordCourse> studentLeaveApplyQueryWrapper = new QueryWrapper<>();
                studentLeaveApplyQueryWrapper.eq("scheduling_detail_id", schedulingDetailId);
                studentLeaveApplyQueryWrapper.eq("student_id", studentId);
                studentLeaveApplyQueryWrapper.last("limit 1");
                RecordCourse recordCourse = iRecordCourseService.getOne(studentLeaveApplyQueryWrapper);
                if (recordCourse != null && recordCourse.getStatus().equals(StatusRecordEnum.LEAVE)) {
                    recordCourse.setStatus(StatusRecordEnum.Truancy);//改为旷课
                    iAdminFeignClient.checkRecordStatus(recordCourse);
                }
            } catch (Exception e) {

            }
            rs = studentLeaveApplyService.updateById(studentLeaveApply);
            return new Result(Code.UPDATE_OK, "", "已拒绝请假申请");
        }

        return new Result(Code.ERROR, "", "未对请假做处理！");
    }

}
